//
//  WebViewController.m
//  WY
//
//  Created by lanou3g on 16/5/11.
//  Copyright © 2016年 pcc. All rights reserved.
//

#import "WebViewController.h"
#import "HTTPManager.h"

#import "CommentController.h"
#import "DBManager.h"
@interface WebViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, copy) NSString *body; // News content
@property (nonatomic, copy) NSString *newsTitle; // News title
@property (nonatomic, copy) NSString *time; // News time

@property (nonatomic, strong) NSString *html;

@end

@implementation WebViewController


- (void)loadView {
    self.webView = [[UIWebView alloc] init];
    self.webView.delegate = self;
    self.view = self.webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 如果不写的画，在跳转到详情控制器的时候，会出现卡顿的现象，这种情况在以后工作中会经常用到，一般都直接把背景设置成白色
    self.view.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
    [self loadData];
    
    self.html = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/%@/full.html",self.model.docid];
    
    NSString *collectTitle = nil;
        
        if ([[DBManager defaultManager]isCollect:self.model.docid]) {
            collectTitle = @"取消收藏";
        }else {
            collectTitle = @"收藏";
        }

        UIBarButtonItem *comment = [[UIBarButtonItem alloc]initWithTitle:@"评论" style:UIBarButtonItemStylePlain target:self action:@selector(commentAction)];
    UIBarButtonItem *collect = [[UIBarButtonItem alloc]initWithTitle:collectTitle style:UIBarButtonItemStylePlain target:self action:@selector(collectActionWithItem:)];
    UIBarButtonItem *share = [[UIBarButtonItem alloc]initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(shareAction)];
    self.navigationItem.rightBarButtonItems = @[comment,collect,share];
  
    //字体
    [[UIBarButtonItem appearance]setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:16.0]} forState:UIControlStateNormal ];
    //返回图标
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
}

//评论
- (void)commentAction {
    CommentController *commentVC = [[CommentController alloc]init];
    commentVC.boardID = self.model.boardid;
    commentVC.docID = self.model.docid;
    [self.navigationController pushViewController:commentVC animated:YES];
}
//收藏
- (void)collectActionWithItem:(UIBarButtonItem *)item {
    if ([[UserInfoManager getUserAuth] isEqualToString:@""]) {
        //先去登陆
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"登录提示" message:@"您还没登陆,请先登录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAC = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *alertAC1 = [UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIStoryboard *sb =[UIStoryboard storyboardWithName:@"Login" bundle:nil];
            LoginController *logiVC = [[LoginController alloc]init];
            logiVC = [sb instantiateViewControllerWithIdentifier:@"login"];
            logiVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            [self presentViewController:logiVC animated:YES completion:nil];
        }];
        [alertVC addAction:alertAC];
        [alertVC addAction:alertAC1];
        [self presentViewController:alertVC animated:YES completion:^{
            
        }];

    }else {
        if ([item.title isEqualToString:@"收藏"]) {
            [item setTitle:@"取消收藏"];
            [[DBManager defaultManager]collectDetailModel:self.model Html:self.html];
        }else {
            [item.title isEqualToString:@"取消收藏"];
            [item setTitle:@"收藏"];
            [[DBManager defaultManager]cancelCollect:self.model.docid];
        }
    }
    


}
//分享
- (void)shareAction {
    if (![[UserInfoManager getUserAuth]isEqualToString:@""]) {
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:UMAPPK
                                          shareText:[NSString stringWithFormat:@"%@: %@",self.model.title,self.model.fullURL]
                                         shareImage:[UIImage imageNamed:self.model.imgsrc]
         //分享图片没出现????没缓存??
                                    shareToSnsNames:@[UMShareToSina,UMShareToWechatSession,UMShareToQQ,UMShareToDouban,UMShareToEmail,UMShareToRenren]
                                           delegate:self];
    }else {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"登录提示" message:@"您还没登陆,请先登录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAC = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *alertAC1 = [UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIStoryboard *sb =[UIStoryboard storyboardWithName:@"Login" bundle:nil];
            LoginController *logiVC = [[LoginController alloc]init];
            logiVC = [sb instantiateViewControllerWithIdentifier:@"login"];
            logiVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            [self presentViewController:logiVC animated:YES completion:nil];
        }];
        [alertVC addAction:alertAC];
        [alertVC addAction:alertAC1];
        [self presentViewController:alertVC animated:YES completion:^{
            
        }];
        
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadData {
    [[HTTPManager shareManager] GET:self.model.fullURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) {
        NSString *key = responseObject.keyEnumerator.nextObject;
        NSDictionary *result = responseObject[key];
        // Take out body content
        __block NSString *body = result[@"body"];
        // Take out all of image
        NSArray *images = result[@"img"];
        // The replacement cycle of image data
        [images enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *ref = obj[@"ref"];
            // Replace character string
            body = [body stringByReplacingOccurrencesOfString:ref withString:[self imageHTMLWithDict:obj]];
        }];
        // Replace video
        NSArray *videos = result[@"video"];
        [videos enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *ref = obj[@"ref"];
            body = [body stringByReplacingOccurrencesOfString:ref withString:[self videoHTMLWithDict:obj]];
        }];
        
        self.body = body;
        self.newsTitle = result[@"title"];
        self.time = [NSString stringWithFormat:@"%@ %@",result[@"ptime"],result[@"source"]];
        // Local html file path
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"detail.html" withExtension:nil];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
      
        [self.webView loadRequest:request];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"出错了");
    }];
}

#pragma mark - image and video 的拼接
- (NSString *)imageHTMLWithDict:(NSDictionary *)dict {
    NSString *html = [NSString stringWithFormat:@"<img src=\"%@\" width=\"100%%\"  alt=\"%@\"/><span style=\"font-size: 13px;color: dimgrey\">%@</span>",dict[@"src"],dict[@"alt"],dict[@"alt"]];
    return html;
}

- (NSString *)videoHTMLWithDict:(NSDictionary *)dict {
    NSString *html = [NSString stringWithFormat:@"<video width=\"100%%\" controls>"
                      "<source src=\"%@\""
                      " type=\"video/mp4\">"
                      "您的浏览器不支持 HTML5 video 标签。"
                      "</video><span style=\"font-size: 13px;color: dimgrey\">%@</span>",dict[@"url_mp4"],dict[@"alt"]];
    return html;
}

#pragma mark - UIWebView 的代理
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *code = [NSString stringWithFormat:@"changeContent('%@', '%@', '%@')",self.newsTitle,self.time,self.body];
    [webView stringByEvaluatingJavaScriptFromString:code];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
